#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/6/27 15:27
# @Author : 闫峰
# @File    : offerdetails.py

import uuid
import requests
from urllib import parse

from api.allegro.get_token import get_token_allegro
from third_services.allegro.RebatyesAndPromotions.baseutils import get_token
from retrying import retry
from utils.mysqlUtils.mongodb_utils import MongoDBLink
from utils.times_tool.time_control import count_time

user = parse.quote_plus("admin")
passwd = parse.quote_plus("Zhcx@2023#MonDb")
modb1 = MongoDBLink(
    uri=f'mongodb://{user}:{passwd}@116.205.233.77:8807/?authSource=admin',
    dbname='walmart_api_table', coll_name='web_logs_allegro')


class OfferDetails:

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def get_offer_details(self, orderSourceid, offerId):
        """
        根据offerid拉取指定Listing信息
        https://developer.allegro.pl/documentation#operation/getProductOffer
        :param orderSourceid:
        :param offerId:
        :return:
        """
        url = f"https://api.allegro.pl/sale/product-offers/{offerId}"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token_allegro(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    @count_time
    def get_offer(self, orderSourceid, limit, type, from_=None):
        """
        增量拉取
        """
        if from_:
            # url = f"https://api.allegro.pl/sale/offer-events?from={from_}&limit=500&type=OFFER_ACTIVATED,OFFER_ENDED,OFFER_PRICE_CHANGED,OFFER_STOCK_CHANGED,OFFER_VISIBILITY_CHANGED"
            # url = f"https://api.allegro.pl/sale/offer-events?from={from_}&limit={limit}&type=OFFER_ACTIVATED,OFFER_ENDED"
            url = f"https://api.allegro.pl/sale/offer-events?from={from_}&limit={limit}&type={type}"
        else:
            # url = f"https://api.allegro.pl/sale/offer-events?limit=500&type=OFFER_ACTIVATED,OFFER_ENDED,OFFER_PRICE_CHANGED,OFFER_STOCK_CHANGED,OFFER_VISIBILITY_CHANGED"
            url = f"https://api.allegro.pl/sale/offer-events?limit={limit}&type={type}"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    @count_time
    def get_offers(self, orderSourceid, offset, limit, status):
        """
        全量拉取
        https://developer.allegro.pl/documentation#operation/searchOffersUsingGET
        """
        # "publication.status": Items Enum: "INACTIVE" "ACTIVE" "ACTIVATING" "ENDED"
        url = f'https://api.allegro.pl/sale/offers?offset={offset}&limit={limit}'
        param = {
            "publication.status": status

        }
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers, params=param, timeout=20)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def get_offer_variants(self, orderSourceid, offset):
        """
        全量拉取setid
        """
        url = f'https://api.allegro.pl/sale/offer-variants?offset={offset}&limit=50'
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers, timeout=20)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def get_offer_variants_set(self, orderSourceid, setId):
        """
        获取变体集合
        """
        url = f'https://api.allegro.pl/sale/offer-variants/{setId}'
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def get_offer_publication_commands_tasks(self, orderSourceid, command_id):
        url = f"https://api.allegro.pl/sale/offer-publication-commands/{command_id}/tasks"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def put_unpublish_offer(self, orderSourceid,offer_id):
        url = f"https://api.allegro.pl/sale/offer-publication-commands/{str(uuid.uuid4())}"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Content-Type": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        requests_json = {
            "offerCriteria": [
                {
                    "offers": [
                        {
                            "id": offer_id
                        }
                    ],
                    "type": "CONTAINS_OFFERS"
                }
            ],
            "publication": {
                "action": "END",
                "scheduledFor": "2024-08-19T09:40:45.367Z"
            }
}
        res = requests.put(url=url, headers=headers, json=requests_json)
        return res
        # try:
        #     if res.status_code == 201:
        #         return res
        # except Exception as e:
        #     raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def get_offer_price_change_commands_tasks(self, orderSourceid, command_id):
        url = f"https://api.allegro.pl/sale/offer-price-change-commands/{command_id}/tasks"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        param = {
            "limit": 1000,
            "offset": 0
        }
        res = requests.get(url=url, headers=headers, params=param)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def return_policies(self, orderSourceid):
        """
        获取退货政策
        :param orderSourceid:
        :return:
        """
        url = f"https://api.allegro.pl/after-sales-service-conditions/return-policies"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        param = {
            "limit": 1000,
            "offset": 0
        }
        res = requests.get(url=url, headers=headers, params=param)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def implied_warranties(self, orderSourceid):
        # https://api.{environment}/after-sales-service-conditions/implied-warranties
        """
        获取投诉政策
        :param orderSourceid:
        :return:
        """
        url = f"https://api.allegro.pl/after-sales-service-conditions/implied-warranties"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        param = {
            "limit": 1000,
            "offset": 0
        }
        res = requests.get(url=url, headers=headers, params=param)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def shipping_rates(self, orderSourceid):
        # https://api.{environment}/sale/shipping-rates
        """
        获取交货价格表
        :param orderSourceid:
        :return:
        """
        url = f"https://api.allegro.pl/sale/shipping-rates"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        param = {
            "limit": 1000,
            "offset": 0
        }
        res = requests.get(url=url, headers=headers, params=param)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def sale_loyalty_promotions(self, orderSourceid):
        # https://api.{environment}/sale/shipping-rates
        """
        获取批发价目表
        :param orderSourceid:
        :return:
        """
        url = f"https://api.allegro.pl/sale/loyalty/promotions?promotionType=WHOLESALE_PRICE_LIST"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        # param = {
        #     "promotionType": "WHOLESALE_PRICE_LIST",
        # }
        res = requests.get(url=url, headers=headers)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def update_offer(self, orderSourceid, offerId):
        """
        编辑offer
        :param orderSourceid:
        :param offerId:
        :return:
        """
        url = f"https://api.allegro.pl/sale/product-offers/{offerId}"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US",
            "Content-Type": "application/vnd.allegro.public.v1+json"
        }

        data = {"language": "en-US", "offerId": 14232600960, "productSet": [{"quantity": {"value": 1}}],
                "stock": {"available": 100, "unit": "UNIT"}}
        data = {"language": "en-US", "offerId": 15844735400, "productSet": [{"quantity": {"value": 1}}],
                "id": "15844735400"}
        res = requests.patch(url=url, headers=headers, json=data)
        """
        返回的例子：
        {'name': 'WATER SPRINKLER AUTOMATIC DEGREE ROTATING TRIPOD 1', 'productSet': [{'product': {'id': '42f88edf-def7-45f1-a4d8-5eac523b084c', 'publication': {'status': 'LISTED'}, 'parameters': [{'id': '224017', 'name': "Manufacturer's code", 'values': ['10347586'], 'valuesIds': None, 'rangeValue': None}, {'id': '246061', 'name': 'Brand', 'values': ['no brand'], 'valuesIds': ['246061_1667754'], 'rangeValue': None}]}, 'quantity': {'value': 1}, 'responsiblePerson': None}], 'parameters': [{'id': '11323', 'name': 'Condition', 'values': ['New'], 'valuesIds': ['11323_1'], 'rangeValue': None}], 'images': ['https://a.allegroimg.com/original/11dca7/f62b560440c5b8a86199d1cc6e64', 'https://a.allegroimg.com/original/11ef1d/556f90a647108e2f7a18e1b1b50e', 'https://a.allegroimg.com/original/110b87/34208c8b4822a490d453018fd7f5', 'https://a.allegroimg.com/original/110af7/8bba4d1b46798ec8f336f4e54546', 'https://a.allegroimg.com/original/1161e5/487769c0404687514523da8d015d', 'https://a.allegroimg.com/original/11e49c/cd9afb5a411bb36ddb951e7d5f86', 'https://a.allegroimg.com/original/11364d/7f947d7f45b88d97b396095cb0c0', 'https://a.allegroimg.com/original/11f764/4124421c45f585d0a55fd69b5d1a'], 'afterSalesServices': {'impliedWarranty': {'id': '41c27d1e-7ecd-4893-92c8-45ffaeb30020'}, 'returnPolicy': {'id': 'e61c66e3-2f8f-4011-9176-413b4f3926b7'}, 'warranty': None}, 'payments': {'invoice': 'NO_INVOICE'}, 'sellingMode': {'format': 'BUY_NOW', 'price': {'amount': '60.12', 'currency': 'PLN'}, 'startingPrice': None, 'minimalPrice': None}, 'stock': {'available': 199, 'unit': 'UNIT'}, 'location': {'countryCode': 'CN', 'province': None, 'city': 'Shenzhen', 'postCode': '518000'}, 'delivery': {'shippingRates': {'id': '1d8de0d8-e8eb-4a15-b53e-0e19bed81040'}, 'handlingTime': 'PT48H', 'additionalInfo': None, 'shipmentDate': None}, 'description': {'sections': [{'items': [{'type': 'TEXT', 'content': '<h2>⭐AGRICULTURAL IRRIGATION WATERING TOOL</h2><h2>⭐ AUTOMATIC ROTATING SPRINKLER</h2><h2>⭐ GARDENING TOOLS</h2><h2>⭐ 360 DEGREE ROTATING SPRINKLER</h2><h2>⭐ ROTATING WATER SPRINKLER</h2>'}, {'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/11dca7/f62b560440c5b8a86199d1cc6e64'}]}, {'items': [{'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/11ef1d/556f90a647108e2f7a18e1b1b50e'}, {'type': 'TEXT', 'content': '<h2>⭐ AGRICULTURAL IRRIGATION WATERING TOOL</h2><p>✅Hydraulically driven 360 degree rotating spray direct spray and oblique spray.</p><p>✅The spraying diameter is about 8-10m and the spraying range is different with different water pressures.</p><p>✅Easy and convenient to use, it is a good helper for your lawn irrigation and garden watering.</p><p>✅360 degree rotating automatic sprinkler, through the pipeline and then through the nozzle precipitation dial and then shoot into the air, easy to use.</p><p>✅Adjustable angle of rotating nozzle in two modes for your different needs.</p>'}]}, {'items': [{'type': 'TEXT', 'content': '<h2>⭐ PACKAGE LIST</h2><p></p><p>✅1 x sprinkler</p><p>✅2 x 3/4 inch connectors</p><p>✅1 x 1/2 and 3/4 inch connector</p><p>✅1 x universal connector</p>'}, {'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/110b87/34208c8b4822a490d453018fd7f5'}]}, {'items': [{'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/110af7/8bba4d1b46798ec8f336f4e54546'}, {'type': 'TEXT', 'content': "<h2>⭐  AUTOMATIC ROTATING SPRINKLER</h2><p>✅If you've been looking for an agricultural irrigation</p><p>✅spinning sprinkler, then your search is over! That's because our product can</p><p>✅provide great help in watering farm, garden, orchard, and other place.</p>"}]}, {'items': [{'type': 'TEXT', 'content': '<h2>⭐  GARDENING TOOLS</h2><p>✅Color: Yellow</p><p>✅Material: ABS</p><p>✅Size: 20.50X18.00X9.00cm/8.06X7.07X3.54in</p><p>✅ Hydraulically driven 360 degree rotating</p><p>✅spray and oblique spray.</p><p>✅ The spraying diameter is about 810m and</p><p>✅the spraying range is different with different water pressures.</p><p>✅ Easy and convenient to use, it is a good</p><p>✅helper for your lawn irrigation and garden watering.</p><p>✅ 360 degree rotating automatic sprinkler,</p><p>✅through the pipeline and then through the nozzle precipitation dial and then</p><p>✅shoot into the air, easy to use.</p><p>✅ Adjustable angle of rotating nozzle in</p><p>✅two modes for your different needs.</p><p>✅</p>'}, {'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/1161e5/487769c0404687514523da8d015d'}]}, {'items': [{'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/11e49c/cd9afb5a411bb36ddb951e7d5f86'}, {'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/11364d/7f947d7f45b88d97b396095cb0c0'}]}]}, 'external': {'id': 'E7143115ETR7DFEO'}, 'category': {'id': '320626'}, 'tax': None, 'taxSettings': None, 'sizeTable': None, 'discounts': {'wholesalePriceList': None}, 'contact': None, 'fundraisingCampaign': None, 'messageToSellerSettings': None, 'attachments': [], 'b2b': None, 'additionalServices': None, 'compatibilityList': None, 'additionalMarketplaces': {'allegro-cz': {'sellingMode': {'price': {'amount': '328.00', 'currency': 'CZK'}}, 'publication': {'state': 'PENDING', 'refusalReasons': []}}, 'allegro-sk': {'sellingMode': {'price': {'amount': '13.95', 'currency': 'EUR'}}, 'publication': {'state': 'PENDING', 'refusalReasons': []}}, 'allegro-business-cz': {'sellingMode': None, 'publication': {'state': 'NOT_REQUESTED', 'refusalReasons': []}}}, 'id': '15867688638', 'language': 'en-US', 'publication': {'status': 'ACTIVE', 'duration': None, 'endedBy': None, 'endingAt': None, 'startingAt': None, 'republish': False, 'marketplaces': {'base': {'id': 'allegro-pl'}, 'additional': [{'id': 'allegro-sk'}, {'id': 'allegro-cz'}]}}, 'validation': {'errors': [], 'warnings': [], 'validatedAt': '2024-07-02T07:33:56.053Z'}, 'createdAt': '2024-06-18T06:33:49.000Z', 'updatedAt': '2024-07-02T07:33:56.054Z'}
        """
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    def publish_offer(self, orderSourceid):
        """
        编辑offer
        :param orderSourceid:
        :param offerId:
        :return:
        """
        url = f"https://api.allegro.pl/sale/product-offers"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US",
            "Content-Type": "application/vnd.allegro.public.v1+json"
        }

        data = {
            "accessToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiIxMTI5ODY4ODYiLCJzY29wZSI6WyJhbGxlZ3JvOmFwaTpvcmRlcnM6cmVhZCIsImFsbGVncm86YXBpOmZ1bGZpbGxtZW50OnJlYWQiLCJhbGxlZ3JvOmFwaTpwcm9maWxlOndyaXRlIiwiYWxsZWdybzphcGk6ZnVsZmlsbG1lbnQ6d3JpdGUiLCJhbGxlZ3JvOmFwaTpzYWxlOm9mZmVyczp3cml0ZSIsImFsbGVncm86YXBpOmJpbGxpbmc6cmVhZCIsImFsbGVncm86YXBpOmNhbXBhaWducyIsImFsbGVncm86YXBpOmRpc3B1dGVzIiwiYWxsZWdybzphcGk6c2FsZTpvZmZlcnM6cmVhZCIsImFsbGVncm86YXBpOmJpZHMiLCJhbGxlZ3JvOmFwaTpvcmRlcnM6d3JpdGUiLCJhbGxlZ3JvOmFwaTpwYXltZW50czp3cml0ZSIsImFsbGVncm86YXBpOnNhbGU6c2V0dGluZ3M6d3JpdGUiLCJhbGxlZ3JvOmFwaTpwcm9maWxlOnJlYWQiLCJhbGxlZ3JvOmFwaTpyYXRpbmdzIiwiYWxsZWdybzphcGk6c2FsZTpzZXR0aW5nczpyZWFkIiwiYWxsZWdybzphcGk6cGF5bWVudHM6cmVhZCIsImFsbGVncm86YXBpOm1lc3NhZ2luZyJdLCJhbGxlZ3JvX2FwaSI6dHJ1ZSwiaXNzIjoiaHR0cHM6Ly9hbGxlZ3JvLnBsIiwiZXhwIjoxNzIyNTQxMTIxLCJqdGkiOiJlNzZiODBiMy01ZDNkLTQ3NjgtODZmOS1hZWU2ZDljNmIzOGQiLCJjbGllbnRfaWQiOiJhZGFkYzU5MjI3Y2M0NTVkODcxMTIwYWQwNGZmMmI5NSJ9.oUam8xYDSQKwQR3OxAfyH9QkhEZCOK16UZZ_8Q1YlmJ0D1t6ycbUnwfosETEm_-AsZDHazfG0aaGDQKQyjxGAB-3WqbRaPAKkZjpDgs43SOlLuHwvrfuq2dxHdMzAV8FkoDBKedvCoJqxJw2U7a5EBGDLn08c8b7J6lgYiUWfFSOI0XgdEE2xfeNJoXL2qti5p-94wVrrSV1uMl0Z3KPyflAZN-5QflBjsT1U6J-ZH28ptmYlt6g1ILavaMHjxuedddhDiAw-X9_a-REZLHj79hzwSWvg_wWigpODuLORkpxfWRf50B2mYI_gy3zE9E7XpDGXmylh4Ql1KRfmQNEVA",
            "additionalMarketplaces": {
                "allegro-cz": {
                    "sellingMode": {
                        "price": {
                            "amount": "186",
                            "currency": "CZK"
                        }
                    }
                }
            },
            "afterSalesServices": {
                "impliedWarranty": {
                    "id": "c924e186-1509-4350-8a4d-39d947c53ace",
                    "name": "Complaint cause"
                },
                "returnPolicy": {
                    "id": "83115ee8-ce50-48b6-beca-437c5cd91067",
                    "name": "MBB Return policy"
                }
            },
            "b2b": {
                "buyableOnlyByBusiness": False
            },
            "category": {
                "id": "93056"
            },
            "customerId": 1,
            "delivery": {
                "handlingTime": "PT24H",
                "shippingRates": {
                    "id": "8fff046b-060c-4bc4-8a09-5b4d027205d2",
                    "name": "One Fulfillment International"
                }
            },
            "description": {
                "sections": [
                    {
                        "items": [
                            {
                                "content": "<h2>✅EXFOLIATING BATH GLOVES</h2><h2>✅SHOWER GLOVES</h2><h2>✅BODY SCRUB EXFOLIATOR</h2><h2>✅NYLON SHOWER GLOVES</h2>",
                                "type": "TEXT"
                            },
                            {
                                "type": "IMAGE",
                                "url": "https://a.allegroimg.com/original/111d47/f66fe79c42c3b2d9914886c1dbd8"
                            }
                        ]
                    },
                    {
                        "items": [
                            {
                                "type": "IMAGE",
                                "url": "https://a.allegroimg.com/original/11c766/b40a31d244e09021dc582bbf94d9"
                            },
                            {
                                "content": "<h1>⭐EXFOLIATING BATH GLOVES</h1><p>✅Easy to put on and take off, loose cuff.</p><p>✅Excellent to work with soap, body , shower gels, or sea salts.</p><p>✅The inside and outside are of the same material so it can be used on both sides.</p><p>✅Stretchy, one size fits most hands.</p><p>✅Textured exfoliating gloves can remove dead skin and dust more efficiently.</p>",
                                "type": "TEXT"
                            }
                        ]
                    },
                    {
                        "items": [
                            {
                                "content": "<h1>⭐PACKING LIST</h1><p>✅1 x Pair of Bath Gloves</p>",
                                "type": "TEXT"
                            },
                            {
                                "type": "IMAGE",
                                "url": "https://a.allegroimg.com/original/1189b1/eafab79440369aa041def3c91831"
                            }
                        ]
                    },
                    {
                        "items": [
                            {
                                "type": "IMAGE",
                                "url": "https://a.allegroimg.com/original/11288a/9fbec6c142ddb74fde0af438cdbf"
                            },
                            {
                                "content": "<h1>⭐SHOWER GLOVES</h1><p>✅Made of premium material</p><p>✅these glvoes are suitable for cleansing and exfoliating skin. your hand into this easytouse bath glove</p><p>✅moisten and squeeze on a of your body wash or soap. Gloves are made of the same material inside and outside and can be used on both sides. Make the most of your shower time with bath mitt and enjoy your shower!Feature Color: Purple. Material: Polyester. Size: Approx. 19x13x1cm Easy to put on and take off</p><p>✅loose cuff. Excellent to work with soap</p><p>✅body</p><p>✅shower gels</p><p>✅or sea salts. The inside and outside are of the same material so it can be used on both sides. Stretchy</p><p>✅one size fits most hands. Textured exfoliating gloves can remove dead skin and dust more efficiently.</p>",
                                "type": "TEXT"
                            }
                        ]
                    },
                    {
                        "items": [
                            {
                                "content": "<h1>⭐BODY SCRUB EXFOLIATOR</h1>",
                                "type": "TEXT"
                            },
                            {
                                "type": "IMAGE",
                                "url": "https://a.allegroimg.com/original/118d42/cc277baa447bab2f9a588f444e15"
                            }
                        ]
                    },
                    {
                        "items": [
                            {
                                "type": "IMAGE",
                                "url": "https://a.allegroimg.com/original/11fc3e/d91ce6184118a0a05e0efe301d6f"
                            },
                            {
                                "type": "IMAGE",
                                "url": "https://a.allegroimg.com/original/11b668/b2544cc14075a0860e519e015b46"
                            }
                        ]
                    }
                ]
            },
            "discounts": {},
            "external": {
                "id": "I1982140051G0P2YCN"
            },
            "images": [
                "https://a.allegroimg.com/original/111d47/f66fe79c42c3b2d9914886c1dbd8",
                "https://a.allegroimg.com/original/11c766/b40a31d244e09021dc582bbf94d9",
                "https://a.allegroimg.com/original/1137c1/a045803545268f36eddf1dc4884d",
                "https://a.allegroimg.com/original/11b668/b2544cc14075a0860e519e015b46",
                "https://a.allegroimg.com/original/11288a/9fbec6c142ddb74fde0af438cdbf",
                "https://a.allegroimg.com/original/11fc3e/d91ce6184118a0a05e0efe301d6f",
                "https://a.allegroimg.com/original/11aca4/e35a97e442cab4d9701c39954853",
                "https://a.allegroimg.com/original/1186d9/b8c382884954be107108ff77dc3d",
                "https://a.allegroimg.com/original/118d42/cc277baa447bab2f9a588f444e15",
                "https://a.allegroimg.com/original/1189b1/eafab79440369aa041def3c91831",
                "https://a.allegroimg.com/original/11d9d5/b103e8c44209b08f37f646506041"
            ],
            "language": "en-US",
            "location": {
                "city": "Adamów 50",
                "countryCode": "PL",
                "postCode": "05-825",
                "province": "MAZOWIECKIE"
            },
            "messageToSellerSettings": {
                "mode": "OPTIONAL"
            },
            "name": "PAIR OF SHOWER EXFOLIATING BATH GLOVES SEAMLESS SHOWER GLOVES BODY EXFOLIAT",
            "parameters": [
                {
                    "id": "11323",
                    "name": "Condition",
                    "valuesIds": [
                        "11323_1"
                    ]
                },
                {
                    "id": "224017",
                    "name": "Manufacturer's code",
                    "values": [
                        "G7VC467"
                    ]
                },
                {
                    "id": "17448",
                    "name": "Weight (with packaging)",
                    "values": [
                        "0.51"
                    ]
                }
            ],
            "payments": {
                "invoice": "NO_INVOICE"
            },
            "productSet": [
                {
                    "product": {
                        "category": {
                            "id": "93056"
                        },
                        "images": [
                            "https://a.allegroimg.com/original/111d47/f66fe79c42c3b2d9914886c1dbd8",
                            "https://a.allegroimg.com/original/11c766/b40a31d244e09021dc582bbf94d9",
                            "https://a.allegroimg.com/original/1137c1/a045803545268f36eddf1dc4884d",
                            "https://a.allegroimg.com/original/11b668/b2544cc14075a0860e519e015b46",
                            "https://a.allegroimg.com/original/11288a/9fbec6c142ddb74fde0af438cdbf",
                            "https://a.allegroimg.com/original/11fc3e/d91ce6184118a0a05e0efe301d6f",
                            "https://a.allegroimg.com/original/11aca4/e35a97e442cab4d9701c39954853",
                            "https://a.allegroimg.com/original/1186d9/b8c382884954be107108ff77dc3d",
                            "https://a.allegroimg.com/original/118d42/cc277baa447bab2f9a588f444e15",
                            "https://a.allegroimg.com/original/1189b1/eafab79440369aa041def3c91831",
                            "https://a.allegroimg.com/original/11d9d5/b103e8c44209b08f37f646506041"
                        ],
                        "name": "PAIR OF SHOWER EXFOLIATING BATH GLOVES SEAMLESS SHOWER GLOVES BODY EXFOLIAT",
                        "parameters": [
                            {
                                "id": "129369",
                                "name": "Brand",
                                "valuesIds": [
                                    "129369_1681660"
                                ]
                            },
                            {
                                "id": "129625",
                                "name": "Type",
                                "valuesIds": [
                                    "129625_286597"
                                ]
                            },
                            {
                                "id": "225693",
                                "name": "EAN (GTIN)",
                                "values": [
                                    "4894973888729"
                                ]
                            }
                        ]
                    },
                    "quantity": {
                        "value": 1
                    }
                }
            ],
            "publication": {
                "marketPlace": {
                    "additional": [
                        {
                            "id": "allegro-cz"
                        }
                    ],
                    "base": {
                        "id": "allegro-pl"
                    }
                },
                "republish": False,
                "status": "ACTIVE"
            },
            "sellingMode": {
                "format": "BUY_NOW",
                "price": {
                    "amount": "23.96",
                    "currency": "PLN"
                }
            },
            "sourceId": 20004,
            "stock": {
                "available": 0,
                "unit": "UNIT"
            },
            "taxSettings": {
                "rates": [
                    {
                        "countryCode": "PL",
                        "rate": "23.00"
                    }
                ]
            }
        }
        res = requests.post(url=url, headers=headers, json=data)
        """
        返回的例子：
        {'name': 'WATER SPRINKLER AUTOMATIC DEGREE ROTATING TRIPOD 1', 'productSet': [{'product': {'id': '42f88edf-def7-45f1-a4d8-5eac523b084c', 'publication': {'status': 'LISTED'}, 'parameters': [{'id': '224017', 'name': "Manufacturer's code", 'values': ['10347586'], 'valuesIds': None, 'rangeValue': None}, {'id': '246061', 'name': 'Brand', 'values': ['no brand'], 'valuesIds': ['246061_1667754'], 'rangeValue': None}]}, 'quantity': {'value': 1}, 'responsiblePerson': None}], 'parameters': [{'id': '11323', 'name': 'Condition', 'values': ['New'], 'valuesIds': ['11323_1'], 'rangeValue': None}], 'images': ['https://a.allegroimg.com/original/11dca7/f62b560440c5b8a86199d1cc6e64', 'https://a.allegroimg.com/original/11ef1d/556f90a647108e2f7a18e1b1b50e', 'https://a.allegroimg.com/original/110b87/34208c8b4822a490d453018fd7f5', 'https://a.allegroimg.com/original/110af7/8bba4d1b46798ec8f336f4e54546', 'https://a.allegroimg.com/original/1161e5/487769c0404687514523da8d015d', 'https://a.allegroimg.com/original/11e49c/cd9afb5a411bb36ddb951e7d5f86', 'https://a.allegroimg.com/original/11364d/7f947d7f45b88d97b396095cb0c0', 'https://a.allegroimg.com/original/11f764/4124421c45f585d0a55fd69b5d1a'], 'afterSalesServices': {'impliedWarranty': {'id': '41c27d1e-7ecd-4893-92c8-45ffaeb30020'}, 'returnPolicy': {'id': 'e61c66e3-2f8f-4011-9176-413b4f3926b7'}, 'warranty': None}, 'payments': {'invoice': 'NO_INVOICE'}, 'sellingMode': {'format': 'BUY_NOW', 'price': {'amount': '60.12', 'currency': 'PLN'}, 'startingPrice': None, 'minimalPrice': None}, 'stock': {'available': 199, 'unit': 'UNIT'}, 'location': {'countryCode': 'CN', 'province': None, 'city': 'Shenzhen', 'postCode': '518000'}, 'delivery': {'shippingRates': {'id': '1d8de0d8-e8eb-4a15-b53e-0e19bed81040'}, 'handlingTime': 'PT48H', 'additionalInfo': None, 'shipmentDate': None}, 'description': {'sections': [{'items': [{'type': 'TEXT', 'content': '<h2>⭐AGRICULTURAL IRRIGATION WATERING TOOL</h2><h2>⭐ AUTOMATIC ROTATING SPRINKLER</h2><h2>⭐ GARDENING TOOLS</h2><h2>⭐ 360 DEGREE ROTATING SPRINKLER</h2><h2>⭐ ROTATING WATER SPRINKLER</h2>'}, {'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/11dca7/f62b560440c5b8a86199d1cc6e64'}]}, {'items': [{'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/11ef1d/556f90a647108e2f7a18e1b1b50e'}, {'type': 'TEXT', 'content': '<h2>⭐ AGRICULTURAL IRRIGATION WATERING TOOL</h2><p>✅Hydraulically driven 360 degree rotating spray direct spray and oblique spray.</p><p>✅The spraying diameter is about 8-10m and the spraying range is different with different water pressures.</p><p>✅Easy and convenient to use, it is a good helper for your lawn irrigation and garden watering.</p><p>✅360 degree rotating automatic sprinkler, through the pipeline and then through the nozzle precipitation dial and then shoot into the air, easy to use.</p><p>✅Adjustable angle of rotating nozzle in two modes for your different needs.</p>'}]}, {'items': [{'type': 'TEXT', 'content': '<h2>⭐ PACKAGE LIST</h2><p></p><p>✅1 x sprinkler</p><p>✅2 x 3/4 inch connectors</p><p>✅1 x 1/2 and 3/4 inch connector</p><p>✅1 x universal connector</p>'}, {'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/110b87/34208c8b4822a490d453018fd7f5'}]}, {'items': [{'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/110af7/8bba4d1b46798ec8f336f4e54546'}, {'type': 'TEXT', 'content': "<h2>⭐  AUTOMATIC ROTATING SPRINKLER</h2><p>✅If you've been looking for an agricultural irrigation</p><p>✅spinning sprinkler, then your search is over! That's because our product can</p><p>✅provide great help in watering farm, garden, orchard, and other place.</p>"}]}, {'items': [{'type': 'TEXT', 'content': '<h2>⭐  GARDENING TOOLS</h2><p>✅Color: Yellow</p><p>✅Material: ABS</p><p>✅Size: 20.50X18.00X9.00cm/8.06X7.07X3.54in</p><p>✅ Hydraulically driven 360 degree rotating</p><p>✅spray and oblique spray.</p><p>✅ The spraying diameter is about 810m and</p><p>✅the spraying range is different with different water pressures.</p><p>✅ Easy and convenient to use, it is a good</p><p>✅helper for your lawn irrigation and garden watering.</p><p>✅ 360 degree rotating automatic sprinkler,</p><p>✅through the pipeline and then through the nozzle precipitation dial and then</p><p>✅shoot into the air, easy to use.</p><p>✅ Adjustable angle of rotating nozzle in</p><p>✅two modes for your different needs.</p><p>✅</p>'}, {'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/1161e5/487769c0404687514523da8d015d'}]}, {'items': [{'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/11e49c/cd9afb5a411bb36ddb951e7d5f86'}, {'type': 'IMAGE', 'url': 'https://a.allegroimg.com/original/11364d/7f947d7f45b88d97b396095cb0c0'}]}]}, 'external': {'id': 'E7143115ETR7DFEO'}, 'category': {'id': '320626'}, 'tax': None, 'taxSettings': None, 'sizeTable': None, 'discounts': {'wholesalePriceList': None}, 'contact': None, 'fundraisingCampaign': None, 'messageToSellerSettings': None, 'attachments': [], 'b2b': None, 'additionalServices': None, 'compatibilityList': None, 'additionalMarketplaces': {'allegro-cz': {'sellingMode': {'price': {'amount': '328.00', 'currency': 'CZK'}}, 'publication': {'state': 'PENDING', 'refusalReasons': []}}, 'allegro-sk': {'sellingMode': {'price': {'amount': '13.95', 'currency': 'EUR'}}, 'publication': {'state': 'PENDING', 'refusalReasons': []}}, 'allegro-business-cz': {'sellingMode': None, 'publication': {'state': 'NOT_REQUESTED', 'refusalReasons': []}}}, 'id': '15867688638', 'language': 'en-US', 'publication': {'status': 'ACTIVE', 'duration': None, 'endedBy': None, 'endingAt': None, 'startingAt': None, 'republish': False, 'marketplaces': {'base': {'id': 'allegro-pl'}, 'additional': [{'id': 'allegro-sk'}, {'id': 'allegro-cz'}]}}, 'validation': {'errors': [], 'warnings': [], 'validatedAt': '2024-07-02T07:33:56.053Z'}, 'createdAt': '2024-06-18T06:33:49.000Z', 'updatedAt': '2024-07-02T07:33:56.054Z'}
        """
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    # 获取活动列表
    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def sale_badge_campaigns(self, orderSourceid):
        """
        获取活动列表
        https://developer.allegro.pl/documentation/#operation/badgeCampaigns_get_all
        :param orderSourceid:
        :return:
        """
        url = f"https://api.allegro.pl/sale/badge-campaigns"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers)
        try:
            if res.status_code == 200:
                return res.json()
            else:
                raise Exception(f"status_code!=200")
        except Exception as e:
            raise e

    # 异步结果获取
    def get_sasa(self, orderSourceid):
        url = f"https://api.allegro.pl/sale/product-offers/16172682900/operations/97b541a0-4c99-4cc2-bcc9-33f3b45b4d0d"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    # 获取徽章活动产品列表
    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def get_offer_id_in_badges(self, orderSourceid, campaign_id, offset, limit):
        url = f"https://api.allegro.pl/sale/badge-applications?campaign.id={campaign_id}&offset={offset}&limit={limit}"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=5, wait_fixed=2000)
    def get_sales_badges(self, orderSourceid, offset, limit):
        url = f"https://api.allegro.pl/sale/badges?offset={offset}&limit={limit}"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers,timeout=10)
        # Enum: "IN_VERIFICATION" "WAITING_FOR_PUBLICATION" "ACTIVE" "FINISHED" "DECLINED"
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e


    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def get_sale_products(self, orderSourceid):
        url = f"https://api.allegro.pl/sale/products?mode=GTIN&phrase=4894931000361&includeDrafts=false"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    @retry(stop_max_attempt_number=30, wait_fixed=2000)
    def get_sale_cayegory_enents(self, orderSourceid, from_, limit, type="CATEGORY_DELETED"):
        # Items Enum: "CATEGORY_CREATED" "CATEGORY_RENAMED" "CATEGORY_MOVED" "CATEGORY_DELETED"
        url = f"https://api.allegro.pl/sale/category-events?from={from_}&limit={limit}&type={type}"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US"
        }
        res = requests.get(url=url, headers=headers)
        try:
            if res.status_code == 200:
                return res.json()
        except Exception as e:
            raise e

    # @retry(stop_max_attempt_number=3, wait_fixed=2000)
    def put_offer_price_change_commands(self, orderSourceid, commandId, data):
        #$ https://api.{environment}/sale/offer-price-change-commands/{commandId}
        url = f"https://api.allegro.pl/sale/offer-price-change-commands/{commandId}"
        headers = {
            "Accept": "application/vnd.allegro.public.v1+json",
            "Authorization": get_token(orderSourceid),
            "Accept-Language": "en-US",
            "Content-Type": "application/vnd.allegro.public.v1+json"
        }
        """
        {
                  "modification": {
                    "type": "FIXED_PRICE",
                    "marketplaceId": "allegro-pl"
                    "price":{
                        "amount":"1111"
                        "currency":"PL"
                    }
                  },
                  "offerCriteria": [
                    {
                      "offers": [
                        {
                          "id": "123456789"
                        }
                      ],
                      "type": "CONTAINS_OFFERS"
                    }
                  ]
        }
        """
        res = requests.put(url=url, headers=headers, json=data,timeout=10)
        return res
        # try:
        #     if res.status_code == 201:
        #         return res.json()
        # except Exception as e:
        #     raise e


if __name__ == '__main__':
    # OfferDetails().sale_badge_campaigns(9046)
    # OfferDetails().get_offer_id_in_badges(11412,'ALLDEALS_202409_SK',0,1000)
    # OfferDetails().get_sales_badges(9046,0,5)
    OfferDetails().get_offer_details(9046,"16174162750")

